/**
 * Master Controller
 */

angular.module('NxtMap')
    .controller('CheckCtrl', ['$rootScope', '$scope', '$cookieStore', '$timeout', '$http', 'MapDiagram', 'MapAnalysis', 'MapService', 'ConstService', CheckCtrl]);

function CheckCtrl($rootScope, $scope, $cookieStore, $timeout, $http, MapDiagram, MapAnalysis, MapService, ConstService) {
  $rootScope.loop = 0;
  $rootScope.setShowMap(true);
  MapService.clearMap();
  MapService.clearRfidPonit();
  window.onresize = function() {
      $scope.$apply();
  };

  //选项列表数据
  $scope.hourList = ConstService.hourList;
  $scope.dateList = ConstService.dateList;
  $scope.timeList = ConstService.timeList;
  $scope.weekList = ConstService.weekList;
  $scope.stations = ['海宁公安局'].concat(ConstService.stations);

  //星期复选
  $scope.selectedWeek = ['1', '2', '3', '4', '5', '6', '7'];
  $scope.checkWeek = function (value) {
    var index = $scope.selectedWeek.indexOf(value);
    if(index < 0){
      $scope.selectedWeek.push(value);
    }
    else{
      $scope.selectedWeek.splice(index, 1);
    }
  }
  $scope.haveWeek = function (value) {
    return $scope.selectedWeek.indexOf(value) > -1;
  }

  //查询条件参数
  $scope.option = {
    number: 10,
    opacity: 5,
    size: 5,
    heightBase: 0,
    anaType: 'space',
    dateType: 'custom',
    startDate: new Date('2015/09/01'),
    endDate: new Date('2015/09/03'),
    hourType: '全天',
    startHour: '00',
    endHour: '23',
    station: '海宁公安局',
    spaceCell: 'square',
    timeCell: 'hour',
    showPoint: false
  };
  //计算后的地图数据
  $scope.computeData = {}; 
  //地图几何体数据 
  $scope.infoData = [];
  //原始数据
  $scope.originData = [];
  //图表数据
  $scope.dataMap = {};
  $scope.selectedMap = [];
  $scope.selectedStation = '';
  $scope.promiseList = null;
  $scope.infoIndex = -1;

  $scope.havePartMapName = function () {
    if(!$scope.dataMap.map) {
      return false;
    }
    return !($scope.selectedMap.length == $scope.dataMap.map.length) 
      && !($scope.selectedMap.length == 0);
  } 
  $scope.haveMapName = function (name) {
    if(!$scope.dataMap.map) {
      return false;
    }
    if(name == 'all') {
      return $scope.selectedMap.length == $scope.dataMap.map.length;
    }
    return $scope.selectedMap.indexOf(name) > -1;
  } 
  $scope.selectType = function (name) {
    if(name == 'all') {
      if($scope.selectedMap.length == $scope.dataMap.map.length) {
        $scope.selectedMap = [];
      }
      else {
        for(var i = 0; i < $scope.dataMap.map.length; i++) {
          if($scope.selectedMap.indexOf($scope.dataMap.map[i].name) < 0) {
            $scope.selectedMap.push($scope.dataMap.map[i].name);
          }
        }
      }
    }
    else {
      var indexM = $scope.selectedMap.indexOf(name);
      if(indexM < 0) {
        $scope.selectedMap.push(name);
      }
      else {
        $scope.selectedMap.splice(indexM, 1);
      }
    }
  }

  //切换地图
  $scope.mapType = 0;
  $scope.changeMap = function (value) {
    $scope.mapType = MapService.changeMap($scope.mapType, value);
  } 

  //刷新位置
  $scope.flyHome = function () {
    MapService.flyHome();
    // MapService.setPosition(120.55001, 30.43014, 0.15, - Math.PI / 2);
  }
  $scope.flyHome();

  // 添加实体的点击操作
  var scene = MapService.viewer.scene;
  // handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
  MapService.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
  MapService.handler.setInputAction(function(movement) {
    var pickedObject = scene.drillPick(movement.position);
    var checked = -1;
    if (Cesium.defined(pickedObject)) {
      for(var i = 0; i < pickedObject.length; i++){
        // MapService.viewer.zoomTo(pickedObject[i].id, new Cesium.HeadingPitchRange(0, - Math.PI / 2, 0));
        checked = pickedObject[i].id.name;
      }
    }
    if($scope.infoIndex != checked) {
      $scope.infoIndex = checked;
      // if(checked < 0){
      //   $scope.dataMap = MapAnalysis.countType($scope.infoData.objects, $scope.qhour);
      // }
      // else {
      //   $scope.dataMap = MapAnalysis.countType($scope.infoData[checked].objects, $scope.qhour);
      // }
      // MapDiagram.drawBar('chart1', dataMap);
      // MapDiagram.drawLine('chart2', $scope.dataMap);
    }
    $scope.$apply();
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  $scope.details = [];
  $scope.showDetails = function (index) {
    $scope.details = $scope.infoData[index].objects;
    $scope.tparam = {
      total: $scope.infoData[index].objects.length,
      max: Math.ceil($scope.infoData[index].objects.length / 10),
      pages: [],
      now: 1
    }
    $scope.tparam.pages = generatePageNum($scope.tparam.now, $scope.tparam.max);
    $scope.showInfo = true;
  }
  $scope.goPage = function (value) {
    if(value == 'pre') {
      if($scope.tparam.now > 1) {
        $scope.tparam.now --;
      }
    }
    else if(value == 'next') {
      if($scope.tparam.now < $scope.tparam.max){
        $scope.tparam.now ++;
      }
    }
    else if(value == '···' || value == '··') {
      return;
    }
    else {
      $scope.tparam.now = value;
    }
    $scope.tparam.pages = generatePageNum($scope.tparam.now, $scope.tparam.max);
  }
  function generatePageNum(index, max) {
    var result = [];
    var num = 5;
    if(max < 8){
      var ii = 1;
      while (ii <= max) {
        result.push(ii);
        ii++;
      }
      return result;
    }
    var minv = index - 2, maxv = index + 2;
    if(minv <= 1) {
      maxv = 1 - minv + maxv;
      minv = 1;
    }
    else {
      result.push('··');
    }
    if(maxv >= max) {
      minv = minv - (maxv - max);
      maxv = max;     
    }
    for(var i = minv; i <= maxv; i++){
      result.push(i);
    }
    if(maxv < max) {
      if(maxv < max - 1){
        result.push('···');
      }
      result.push(max);
    }
    return result;
  }

  var url_origin = $rootScope.url_origin + '/checks';
  //图层调整变化监控
  //显示多边形切换
  $scope.$watch('option.spaceCell', function(newValue, oldValue) {
    if($scope.computeData.s != null){
      draw();
    }
  });
  $scope.$watch('option.timeCell', function(newValue, oldValue) {
    if($scope.originData.length > 0){
      var formatParam = judgeType($scope.option.anaType, newValue);
      $scope.computeData = MapAnalysis.compute($scope.originData, formatParam);
      setTimeline($scope.computeData.timelineList);
      draw();
    }
  });
  $scope.$watch('option.number', function(newValue, oldValue) {
    setCss('#number', newValue * 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
  $scope.$watch('option.opacity', function(newValue, oldValue) {
    setCss('#opacity', newValue * 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
  $scope.$watch('option.heightBase', function(newValue, oldValue) {
    setCss('#heightBase', newValue / 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
  $scope.$watch('option.size', function(newValue, oldValue) {
    var percent = (newValue - 1) / 9 * 100;
    setCss('#size', percent);
    $http({
      method: 'POST',
      url: url_origin + '/set',
      data: {s: 0.001 * $scope.option.size}
    }).success(function (resp){
      console.log(resp);
      MapAnalysis.setS(0.001 * $scope.option.size);
    });
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout($scope.submit, 1000);
      
    }
  });
  $scope.$watch('option.showPoint', function(newValue, oldValue) {
    if($scope.originData.length > 0){
      draw();
    }
  })

  //提交查询，返回结果，进行分析，添加图层
  $scope.submit = function () {
    setCss('#number', $scope.option.number * 10);
    setCss('#heightBase', $scope.option.heightBase / 10);
    setCss('#size', ($scope.option.size - 1) / 9 * 100);
    
    var qdate = getDate($scope.option.dateType);
    $scope.qhour = getHour($scope.option.hourType);

    var url_path = '?filter={"where": {"questart": {"between": ["' 
      + qdate[0] + '", "' 
      + qdate[1]
      + '"]}, "xs": {"between": ["' 
      + $scope.qhour[0] + '", "' 
      + $scope.qhour[1]
      + '"]}, "xq": {"inq": [' 
      + $scope.selectedWeek.toString()
      + ']}}}';

    console.log(url_path);
    
    $http.get(url_origin + url_path).success(function (data) {
      console.log(data);
      $scope.originData = data;
      $scope.computeData = MapAnalysis.compute(data);
      console.log($scope.computeData);
      draw();
      $scope.isSummaryFold = false;
    });
    $scope.isSelectorFold = true;
  }

  var draw = function draw() {
    var param = {
      colorIndex: 8,
      heightBase: $scope.option.heightBase,
      opacity: $scope.option.opacity / 10,
      lenPercent: $scope.option.number / 10
    }
    $scope.infoData = MapService.drawMap($scope.option.spaceCell,
      $scope.originData, $scope.computeData, param);
    $scope.infoIndex = -1;
    // $scope.dataMap = MapAnalysis.countType($scope.infoData.objects, $scope.qhour);
    // MapDiagram.drawBar('chart1', dataMap);
    // MapDiagram.drawLine('chart2', $scope.dataMap);
    if($scope.option.showPoint){
      MapService.drawPointGeometry($scope.originData);
    }
  }

  function judgeType(anaType, timeCell) {
    var formatParam = null;
    if(anaType == 'timeSpace') {
      switch (timeCell){
        case 'hour': 
          formatParam = 'HH';
          break;
        case 'week': 
          formatParam = '星期w';
          break;
        case 'month': 
          formatParam = 'MM月';
          break;
        case 'year': 
          formatParam = 'yyyy年';
          break;
      }
    }
    else if(anaType == 'timeOrder'){
      switch (timeCell){
        case 'week': 
          formatParam = 'yyyy年MM月w';
          break;
        case 'month': 
          formatParam = 'yyyy年MM月';
          break;
        case 'year': 
          formatParam = 'yyyy年';
          break;
      }
    }
    return formatParam;
  }

  function getDate(dateType) {
    var start = new Date();
    var end = new Date();
    switch (dateType){
      case 'yesterday':
        start.setDate(start.getDate() - 1);
        end.setDate(end.getDate() + 1);
        break;
      case 'lastweek':
        start.setDate(start.getDate() - start.getDay() - 7);
        end.setDate(end.getDate() - end.getDay());
        break;
      case 'lastmonth':
        start.setDate(1);
        start.setMonth(start.getMonth() - 1);
        end.setDate(1);
        break;
      case 'thisweek':
        start.setDate(start.getDate() - start.getDay());
        end.setDate(end.getDate() + 1);
        break;
      case 'thismonth':
        start.setDate(1);
        end.setDate(end.getDate() + 1);
        break;
      case 'custom':
        start = $scope.option.startDate;
        end = $scope.option.endDate;
        // end.setDate(end.getDate() + 1);
        break;
    }
    return [start.format('yyyy/MM/dd'), end.format('yyyy/MM/dd')];
  }

  function getHour(hourType) {
    if(hourType == '自选时间') {
      return [$scope.option.startHour, $scope.option.endHour]; 
    }
    for(var i = 0; i < $scope.timeList.length; i++){
      if(hourType == $scope.timeList[i].name) {
        return [$scope.timeList[i].start, $scope.timeList[i].end];
      }
    }
  }

  function setCss(elementId, value){
    $(elementId).attr('style','background:-webkit-linear-gradient(360deg, #418CFF ' + value + '%, #ABB7CD ' + value + '%);')
  }

}